package com.fjb.controller.user;


import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fjb.common.entity.HttpCode;
import com.fjb.common.entity.JsonResult;
import com.fjb.common.enums.product.DealType;
import com.fjb.controller.base.BaseController;
import com.fjb.dto.LoginUserInfo;
import com.fjb.pojo.log.SysSmsCodeLog;
import com.fjb.pojo.product.ProductInfo;
import com.fjb.pojo.user.SysUser;
import com.fjb.service.log.SysSmsCodeLogService;
import com.fjb.service.product.ProductInfoService;
import com.fjb.service.user.SysUserService;

/**
 * <p>
 * 用户信息 前端控制器
 * </p>
 *
 * @author hemiao
 * @since 2019-12-22
 */
@Controller
@RequestMapping("/sysUser")
public class SysUserController extends BaseController{
	
	private static final Logger logger = LoggerFactory.getLogger(SysUserController.class);
	
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private ProductInfoService productInfoService;
	@Autowired
	private SysSmsCodeLogService sysSmsCodeLogService;
	
	/**
	 * @Description:用户首页查询
	 * @param request
	 * @return
	 * JsonResult<Map<String,Object>>
	 * @exception:
	 * @author: hemiao
	 * @time:2020年2月16日 下午11:27:22
	 */
	@RequestMapping(value="/selectIndex")
	@ResponseBody
	public JsonResult<Map<String, Object>> selectIndex(HttpServletRequest request){
		HashedMap<String, Object> resultMap = new HashedMap<String, Object>();
		LoginUserInfo userInfo = getBaseWxTokenId(request);
		Integer userId = userInfo.getUserId();
		// 查询我卖的数量
		QueryWrapper<ProductInfo> queryWrapper = new QueryWrapper<ProductInfo>();
		queryWrapper.eq("user_id", userId);
		queryWrapper.eq("deal_type", DealType.TYPE_1.getCode());
		List<ProductInfo> list1 = productInfoService.list(queryWrapper);
		resultMap.put("dealType1Count", list1.size());
				
		// 查询我收购的数量
		QueryWrapper<ProductInfo> queryWrapper2 = new QueryWrapper<ProductInfo>();
		queryWrapper2.eq("user_id", userId);		
		queryWrapper2.eq("deal_type", DealType.TYPE_2.getCode());	
		List<ProductInfo> list2 = productInfoService.list(queryWrapper2);
		resultMap.put("dealType2Count", list2.size());	
			
		// 获得用户定位信息
		/*SysUser sysUser = sysUserService.getById(userId);
		sysUser.setPassword(null);	
		resultMap.put("sysUser", sysUser);	*/
		return new JsonResult<Map<String,Object>>(resultMap, HttpCode.SUCCESS);
	}
	
	/**
	 * @Description:更新 地址 location
	 * @param request
	 * @param latitude
	 * @param longitude
	 * @return
	 * JsonResult<Integer>
	 * @exception:
	 * @author: hemiao
	 * @time:2020年2月16日 下午11:38:06
	 */
	@RequestMapping(value="/updateLocation")
	@ResponseBody
	public JsonResult<Integer> updateLocation(HttpServletRequest request,
			BigDecimal latitude,BigDecimal longitude){
		HttpCode httpCode = HttpCode.PARAM_VERIFICATION;
		if(latitude==null) {
			httpCode.setMsg("纬度不能为空");
			return new JsonResult<Integer>(null, httpCode);
		}
		if(longitude==null) {
			httpCode.setMsg("经度不能为空");
			return new JsonResult<Integer>(null, httpCode);
		}
		String nation = request.getParameter("nation");
		if(StringUtils.isBlank(nation)) {
			httpCode.setMsg("国家不能为空");
			return new JsonResult<Integer>(null, httpCode);
		}
		String province = request.getParameter("province");
		if(StringUtils.isBlank(province)) {
			httpCode.setMsg("省份不能为空");
			return new JsonResult<Integer>(null, httpCode);
		}
		String city = request.getParameter("city");
		if(StringUtils.isBlank(city)) {
			httpCode.setMsg("市不能为空");
			return new JsonResult<Integer>(null, httpCode);
		}
		String district = request.getParameter("district");
		// 街道
		String street = request.getParameter("street");
		// 地址
		String address = request.getParameter("address");
		
		LoginUserInfo userInfo = getBaseWxTokenId(request);
		Integer userId = userInfo.getUserId();
		
		SysUser su = new SysUser();
		su.setId(userId);
		su.setNation(nation);
		su.setProvince(province);
		su.setCity(city);
		if(StringUtils.isBlank(district)) {
			district = ""; 
		}
		if(StringUtils.isBlank(street)) {
			street = ""; 
		}
		if(StringUtils.isBlank(address)) {
			address = ""; 
		}
		LocalDateTime localDateTime = LocalDateTime.now();
		su.setDistrict(district);
		su.setStreet(street);	
		su.setAddress(address);
		su.setLatitude(latitude);
		su.setLongitude(longitude);
		su.setLocationUpdateTime(localDateTime);
		su.setUpdateTime(localDateTime);
		su.setUpdateUserId(userId);
		boolean b = sysUserService.updateById(su);
		if(b==false) {	
			logger.info("获得地址 保存失败 ："+JSON.toJSONString(su));
		}
		return new JsonResult<Integer>(null, HttpCode.SUCCESS);
	}
	
	/**
	 * @Description:绑定手机号
	 * @param request
	 * @return
	 * JsonResult<Boolean>
	 * @exception:
	 * @author: hemiao
	 * @time:2020年2月25日 下午5:52:24
	 */
	@RequestMapping(value="/bangDingPhone")
	@ResponseBody
	public JsonResult<Boolean> bangDingPhone(HttpServletRequest request){
		HttpCode httpCode = HttpCode.PARAM_VERIFICATION;
		String phone = request.getParameter("phone");
		if(StringUtils.isBlank(phone)) {
			httpCode.setMsg("手机号不能为空");
			return new JsonResult<Boolean>(null, httpCode);
		}
		String reqSmsCode = request.getParameter("smsCode");
		if(StringUtils.isBlank(reqSmsCode)) {
			httpCode.setMsg("验证码不能为空");
			return new JsonResult<Boolean>(null, httpCode);
		}
		LoginUserInfo userInfo = getBaseWxTokenId(request);
		Integer userId = userInfo.getUserId();
		
		// 用 userId 和 phone 查询
		QueryWrapper<SysSmsCodeLog> queryWrapper = new QueryWrapper<SysSmsCodeLog>();
		queryWrapper.eq("user_id", userId);
		queryWrapper.eq("phone", phone);
		queryWrapper.eq("sms_status", 1);
		List<SysSmsCodeLog> smsList = sysSmsCodeLogService.list(queryWrapper);
		if(smsList.size()==0) {
			httpCode.setMsg("未找到验证码");
			return new JsonResult<Boolean>(null, httpCode);
		}
		SysSmsCodeLog oldSms = null;
		for (SysSmsCodeLog sms : smsList) {
			String smsCode = sms.getSmsCode();
			if(smsCode.equals(reqSmsCode)) {
				oldSms = sms;
				break;
			}
		}
		if(oldSms==null) {
			httpCode.setMsg("未找到验证码");
			return new JsonResult<Boolean>(null, httpCode);
		}
		LocalDateTime localDateTime = LocalDateTime.now();
		SysUser user = new SysUser();
		user.setId(userId);
		user.setPhone(phone);
		user.setUpdateUserId(userId);
		user.setUpdateTime(localDateTime);
		boolean b = sysUserService.updateById(user);
		if(b==false) {	
			httpCode.setMsg("绑定失败,请联系管理员");
			return new JsonResult<Boolean>(null, httpCode);
		}
		// 删除手机号	
		oldSms.setSmsStatus(2);
		oldSms.setUpdateTime(localDateTime);
		oldSms.setUpdateUserId(userId);
		sysSmsCodeLogService.updateById(oldSms);
		return new JsonResult<Boolean>(null, HttpCode.SUCCESS);
	}
}
